//
//  emoticonViewController.swift
//  表情键盘独立开发
//
//  Created by IOS on 15/8/10.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit

///cell标示
private let TYHEmoticonCellIdentifier = "TYHEmoticonCellIdentifier"

class emoticonViewController: UIViewController {

    ///定义一个选择表情回调的闭包
    var selectedEmoticonCallBack:(emoticon: Emoticon) -> ()
    
    init(selectedEmoticon:(emoticon: Emoticon) -> ()) {
        selectedEmoticonCallBack = selectedEmoticon
        super.init(nibName: nil, bundle: nil)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //选中工具栏按钮
    func clickItem(item: UIBarButtonItem) {
//        print(item.tag)
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
//        view.backgroundColor = UIColor.redColor()
        setupUI()
    }
    
    private func setupUI() {
        view.addSubview(toolbar)
        view.addSubview(collectionView)
        
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict = ["cv": collectionView, "tb": toolbar]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        prepareToolbar()
        prepareCollectionView()
    }
    
    private func prepareCollectionView() {
        collectionView.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: TYHEmoticonCellIdentifier)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.whiteColor()
    }
    
    ///准备工具栏
    private func prepareToolbar() {
        toolbar.tintColor = UIColor.darkGrayColor()
        
        var items = [UIBarButtonItem]()
        var index = 0
        for p in packages {
            items.append(UIBarButtonItem(title: p.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            items.last?.tag = index++
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        
        items.removeLast()
        toolbar.items = items
        
    }
    
    //懒加载
    
    //表情数据包
    private lazy var packages = EmoticonPackage.packages
    private lazy var toolbar = UIToolbar()
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: TYHEmoticonLayout())
    
    ///表情键盘布局,私有类
    private class TYHEmoticonLayout: UICollectionViewFlowLayout {
       private override func prepareLayout() {
            //设置布局属性
            let w = UIScreen.mainScreen().bounds.width / 7.0
            let h = ((collectionView?.bounds.height)! - 3 * w) * 0.499
        
            itemSize = CGSizeMake(w, w)
            sectionInset = UIEdgeInsets(top: h, left: 0, bottom: h, right: 0)
//
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
//
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
        
        }
    
    }
    
    
}

//数据源方法？，，
extension emoticonViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        //完成回调
//        print(emoticon)
        selectedEmoticonCallBack(emoticon: emoticon)
        if indexPath.section != 0 {
        EmoticonPackage.addFavorate(emoticon)
        }
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      return  packages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(TYHEmoticonCellIdentifier, forIndexPath: indexPath) as! EmoticonCell
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.greenColor()
        cell.emoticon = packages[indexPath.section].emoticons![indexPath.row]
        return cell
    }
}

//表情cell
private class EmoticonCell: UICollectionViewCell {
    
    var emoticon: Emoticon? {
        didSet{
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            if emoticon!.removeEmoticon {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        emoticonButton.userInteractionEnabled = false
        contentView.addSubview(emoticonButton)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载
    private lazy var emoticonButton = UIButton()
    
}









